<script setup>
import LfTabs from '@/components/commonUI/LfTabs.vue'
import { useTopicClassListQuery } from '@/composables/useTopicDataQuery'
import TopicExploreList from './TopicExploreList.vue'
import LfButton from '@/components/commonUI/LfButton.vue'
import HotPage from '@/views/HotPage/HotPage.vue'
import { onMounted, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 是否需要重定向
const shouldRedirect = computed(() => !!route.query.token)

// 若有token，立即跳转并不执行后续逻辑
if (shouldRedirect.value) {
  router.replace('/detectionPage?token=' + route.query.token)
}

const activeIndex = ref(0)

// 仅在不跳转时才发起数据请求
let classDataRef = ref(null)
if (!shouldRedirect.value) {
  const { data } = useTopicClassListQuery()
  classDataRef = data
}

const hotPage = ref(null)
const topicClassList = computed(() => {
  const list = classDataRef?.value?.result?.map((item) => ({
    // id: item.cateId,
    // name: item.cateName,
    id: item.id,
    name: item.topicName,
  }))
  list?.unshift({
    id: 0,
    name: '热门',
  })
  //topicId.value = list?.[activeIndex.value]?.id;
  return list
})

const topicId = ref(null)

const changeSubmitType = (index, id, name, scrollLeft) => {
  if (shouldRedirect.value) return
  activeIndex.value = index
  sessionStorage.setItem('topic', index)
  sessionStorage.setItem('scrollLeft', scrollLeft)
  if (index === 0) {
    topicId.value = ''
  } else {
    topicId.value = id
  }
  sessionStorage.setItem('topicId', topicId.value)

}

const topicClassItem = () => {
  if (shouldRedirect.value) return
  router.push(`/topicExploreItem/${topicClassList.value?.[activeIndex.value]?.id}?cateName=${topicClassList.value?.[activeIndex.value]?.name}`)
}
let isShowMore = ref(false)
const displayList = (newVal) => {
  topicId.value = newVal?.map(item => item.id).toString();//cateId
  if (shouldRedirect.value) return
  if (newVal && newVal.length >= 5) {
    isShowMore.value = true
  } else {
    isShowMore.value = false
  }
}

const lfTabsRef = ref(null)
onMounted(() => {
  if (shouldRedirect.value) return
  const activeIdx = sessionStorage.getItem('topic') || 0
  topicId.value = sessionStorage.getItem('topicId') || ''

  if (activeIdx) {
    activeIndex.value = activeIdx * 1
    lfTabsRef.value?.scrollLeftFn(sessionStorage.getItem('scrollLeft'))
  }
})
</script>

<template>
  <div v-if="!shouldRedirect" class="py-8 flex justify-center w-full">
    <div class="w-[80%] max-w-[1600px]">

      <div class="flex gap-2 flex-col">
        <LfTabs :activeIndex="activeIndex" ref="lfTabsRef" :tabOptions="topicClassList"
          :onTopicClick="changeSubmitType" />

        <!-- <TopicExploreList @displayList="displayList" v-if="topicClassList"
          :classId="topicClassList?.[activeIndex]?.id" /> -->
      </div>
      <HotPage ref="hotPage" :topicId="topicId" />
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
